package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.pojos.HistorySearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author DiXiaoNie
 * @since 2023/1/2 16:57
 */
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.根据条件查询历史记录是否存在
        ApUserSearch apUserSearch = this.mongoTemplate.findOne(Query.query(
                Criteria.where("keyword").is(keyword)
                        .and("userId").is(userId)
        ), ApUserSearch.class);

        //2.如果存在  则更新时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            this.mongoTemplate.save(apUserSearch);
            return;
        }
        //3.如果不存在 则判断当前用户下历史记录是否大于10条

        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList = this.mongoTemplate.find(query, ApUserSearch.class);

        //3.5 封装数据
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());
        //4.如果不大于10条 则直接新增
        if (apUserSearchList.size() < 10) {
            this.mongoTemplate.insert(apUserSearch);
        } else {
            //5.如果大于十条，则替换最早的那一条记录
            //获取最后一条数据
            ApUserSearch oldApUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);

            this.mongoTemplate.findAndReplace(Query.query(
                    Criteria.where("id").is(oldApUserSearch.getId())
            ), apUserSearch);
        }

    }

    /**
     * 删除
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/02
     */
    @Override
    public ResponseResult del(HistorySearchDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        this.mongoTemplate.remove(Query.query(
                Criteria.where("id").is(dto.getId())
        ), ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 找到所有
     *
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/02
     */
    @Override
    public ResponseResult load() {
        ApUser apUser = ApThreadLocalUtil.getApUserThreadLocal();
        List<ApUserSearch> list = this.mongoTemplate.find(Query.query(
                Criteria.where("userId").is(apUser.getId())
        ).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(list);
    }
}
